#include <iostream>
#include <pcapgether.h>
#include <requesthandler.h>
#include <unistd.h>
#include <pthread.h>
#include <vector>

using namespace std;

void makedaemon()
{
	pid_t pid;
	if ((pid = fork()) < 0)
		exit(0);
	else if (pid != 0)
		exit(0);
	close(0);
	close(1);

	setsid();
}

int main(int argc, char **argv)
{
	pthread_t thread_i;
	int n;
	int sockfd;

	if (argc != 2)
	{
		printf("Usage: %s [port]\n", argv[0]);
		return 1;
	}
	makedaemon();

	if (n = pthread_create(&thread_i, NULL, pcapgther, (void *)argv[1]) != 0)
	{
		perror("gther thread create error");
		exit(0);
	}

	sockfd = comminit();
	if (sockfd < 0)
	{
		perror("Socket init error");
		exit(0);
	}
	while(1)
	{
		int clientfd;
		clientfd = acceptor(sockfd);
		if (clientfd < 0)
		{
			perror("Accept Error");
			exit(0);
		}
		if (n = pthread_create(&thread_i, NULL, requesthandler, (void *)&clientfd) != 0)
		{
			perror("handler thread create error");
			exit(0);
		}
		pthread_detach(thread_i);
	}
}
